import React from 'react';
import {
    Form,
    Input,
    Button,
} from 'antd-mobile'
//引入接口
import { loginApi } from '@/api/login';
import { Toast } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { updateUserAction } from '@/store/actions/userAction'
const Myloginform = () => {
    const his = useHistory()

    const dispatch = useDispatch()
    // 当提交表单的时候触发
    const onFinish = (values) => {
        console.log(values);
        // 调用登录接口
        loginApi(values).then(res => {
            console.log(res);
            if (res.data.code == 200) {
                //登录成功
                // 01: 提示
                // 02: 数据的存储
                // 03:跳转页面
                Toast.show({
                    icon: 'success',
                    content: res.data.message,
                    duration: 1000,
                    afterClose() {
                        his.push('/home')
                    }
                })

                localStorage.setItem('token', res.data.data.token)
                // 将userId 存放到redux
                dispatch(updateUserAction(res.data.data.userid))

            } else {
                //未登录成功提示
                Toast.show({
                    icon: 'fail',
                    content: res.data.message,
                    duration: 1000,
                })
            }

        })
    }
    return (
        <div>
            <Form
                layout='horizontal'
                onFinish={onFinish}
                footer={
                    <Button block type='submit' color='primary' size='large'>
                        提交
                    </Button>
                }
            >
                <Form.Item
                    name='loginname'
                    label='用户名'
                    rules={[{ required: true, message: '姓名不能为空' }]}
                >
                    <Input onChange={console.log} placeholder='请输入用户名' />
                </Form.Item>
                <Form.Item
                    name='password'
                    label='密码'
                    rules={[{ required: true, message: '密码不能为空' }]}
                >
                    <Input onChange={console.log} placeholder='请输入密码' />
                </Form.Item>
            </Form>

        </div>
    );
}

export default Myloginform;
